package com.self.cloudmall.pms.exception;

import com.self.cloudmall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @version v1.0
 * @ClassName: 全局异常处理
 * @Description:
 */
@RestControllerAdvice
@Slf4j
public class WholeExceptionHandler {

    /**
     * @Title: 校验参数异常处理
     * @Description:
     * @Param [valid]
     * @Return com.self.cloudmall.common.utils.R
     */
    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public R validExcepHandler(MethodArgumentNotValidException valid){
        BindingResult result = valid.getBindingResult();
        FieldError fieldError = result.getFieldError();
        return R.error().put("data",fieldError.getDefaultMessage());
    }

    /**
     * @Title: 公共的异常处理
     * @Description:
     * @Param [ex]
     * @Return com.self.cloudmall.common.utils.R
     */
    @ExceptionHandler(value= Exception.class)
    public R commonExcepHandler(Exception ex){
        log.error("发生异常，异常信息：",ex);
        return R.error().put("data",ex.getMessage());
    }
}
